package com.neuedu.mblog.controller;

import com.alibaba.fastjson.JSON;
import com.neuedu.mblog.dao.UploadFileDao;
import com.neuedu.mblog.entiry.UploadFile;
import com.neuedu.mblog.framework.Constants;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 项目：his
 * 创建时间：  2021/12/15   14:57
 * 作者 :jshand
 * 描述 : 上传文件的Controlle
 */
@WebServlet(urlPatterns = "/upload")
public class UploadController extends HttpServlet {

    private UploadFileDao dao = new UploadFileDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        Integer success = 0;
        String url ="";
        try { //从request中解析 上传的文件

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //如果是文件上传到 请求
            if (isMultipart) {
                UploadFile uploadFile = new UploadFile();

                List<FileItem> items = parseFileItem(request);
                // Process the uploaded items
                Iterator<FileItem> iter = items.iterator();
                if (iter.hasNext()) {
                    FileItem item = iter.next();
                    String filedName = item.getFieldName();//表单控件的名字

                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();


                    //转呗保存到数据库的数据
                    uploadFile.setOriginName(fileName);
                    String ext = fileName.substring(fileName.lastIndexOf("."));
                    //UUID
                    uploadFile.setPath(UUID.randomUUID().toString() + ext);
                    uploadFile.setSize(sizeInBytes);

                    //转储到硬盘中
                    item.write(new File(Constants.UPLOAD_BASE_DIR, uploadFile.getPath()));
                }

                uploadFile.setIp(request.getRemoteAddr());
                //保存到数据库中 ,应该调用service，
                // TODO 暂时偷懒了，没写
                int id = dao.save(uploadFile);
                success = 1;//上传成功了
                url = request.getContextPath()+"/download?id="+id;
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //跳转到列表页




        //对象转json的类库
        Map map = new HashMap();
        map.put("success", success);
        map.put("url", url);
        
        //转成json字符串
        //{"success":1,"url":"\/examples\/php\/..\/uploads\/6.jpg"}
        String json = JSON.toJSONString(map);

        //将JSON结果 发送给前端
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }


    //解析文件对象
    private List<FileItem> parseFileItem(HttpServletRequest request) {
        //按照文件上传的形式解析表单
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext application = this.getServletConfig().getServletContext();
        File repository = (File) application.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //真正解析文件(表单项)的到内存的
        List<FileItem> items = new ArrayList();
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        return items;
    }


}
